﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace FuelDXApplication1
{
    /// <summary>
    /// 检测解析xml
    /// </summary>
    public class XmlFileWatcher
    {
        private FileSystemWatcher _watcher;
        private string _pathToWatch= "D:\\实训一\\FuelDXApplication1\\xml\\fuelData1.xml";
        private string _dbConnectionString;

        public XmlFileWatcher(string pathToWatch, string dbConnectionString)
        {
            _pathToWatch = pathToWatch;
            _dbConnectionString = dbConnectionString;
            InitializeWatcher();
        }

        private void InitializeWatcher()
        {
            _watcher = new FileSystemWatcher(_pathToWatch)
            {
                Filter = "*.xml",
                NotifyFilter = NotifyFilters.LastWrite // 监视文件的最后写入时间
            };
            _watcher.Created += OnXmlFileCreated;
            _watcher.EnableRaisingEvents = true;
        }

        private void OnXmlFileCreated(object sender, FileSystemEventArgs e)
        {
            string xmlFilePath = e.FullPath;
            Console.WriteLine($"New XML file detected: {xmlFilePath}");
            ParseAndStoreXml(xmlFilePath);
        }

        private void ParseAndStoreXml(string xmlFilePath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFilePath);

                // 假设XML结构已知，解析XML并提取数据
                XmlNode rootNode = doc.DocumentElement;
                foreach (XmlNode rowNode in rootNode.SelectNodes("your/row/path"))
                {
                    string data = rowNode.InnerText; // 或者更复杂的数据提取逻辑

                    //// 将数据存储到数据库
                    //StoreDataInDatabase(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing XML file: {ex.Message}");
            }
        }

        //private async void StoreDataInDatabase(string data)
        //{
        //    var results = await DBHelper.Insert(data);
        //}
    }
}
